package com.example.administrator.printoutindemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.example.administrator.printoutindemo.view.MyImageButton;
import com.example.administrator.printoutindemo.zxing.activity.CaptureActivity;


import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.List;


public class StoreQRCScanByZLJY extends Activity {

	private MyImageButton store_btn_QRCode = null;
	private TextView s_qrc_code = null;
	private TextView s_txt_material = null;
	//	private TextView s_txt_mstatus = null;
	private Button s_qrc_btn_scan = null;
	private Mothsked mothsked = null;

	ProgressDialog progressDiaog;

	String scanResult = "";

	private static final String WEBSERVICE_CONFIG = "webServiceInfo";

	private static final int SCANSUCCESS = 0;
	private static final int SCANERROR = 1;

	Handler hanlder = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case SCANSUCCESS:

					s_qrc_code.setText(scanResult);

					Toast.makeText(StoreQRCScanByZLJY.this, "检查成功!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case SCANERROR:

					Toast.makeText(StoreQRCScanByZLJY.this, "检查失败!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_activity_qrcscanbyzljy);

		store_btn_QRCode = (MyImageButton) findViewById(R.id.store_btn_QRCode);
		s_qrc_code = (TextView) findViewById(R.id.s_qrc_code);
		s_txt_material = (TextView) findViewById(R.id.s_txt_material);
//		s_txt_mstatus = (TextView) findViewById(R.id.s_txt_mstatus);
		s_qrc_btn_scan = (Button) findViewById(R.id.s_qrc_btn_scan);

		mothsked = (Mothsked) getIntent().getSerializableExtra("Mothsked");

		s_txt_material.setText(mothsked.getMaterial());


		store_btn_QRCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent openCameraIntent = new Intent(StoreQRCScanByZLJY.this,
						CaptureActivity.class);
				startActivityForResult(openCameraIntent, 0);
			}
		});

		s_qrc_btn_scan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent openCameraIntent = new Intent(StoreQRCScanByZLJY.this,
						CaptureActivity.class);
				startActivityForResult(openCameraIntent, 0);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			scanResult = bundle.getString("result");
			// lbl_QRCode.setText(scanResult);

			progressDiaog = new ProgressDialog(StoreQRCScanByZLJY.this);
			progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
			progressDiaog.setTitle("提示");
			// progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
			progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
			progressDiaog.setIndeterminate(false);// 设置进度条不明确
			progressDiaog.setCancelable(true);

			progressDiaog.show();

			new Thread() {
				@Override
				public void run() {

					if (mothsked != null) {

						List<Mothsked> li_m = new ArrayList<Mothsked>();

						mothsked.setMstatus(5);
						li_m.add(mothsked);

						if (uploadInfo(li_m)) {
							Message m = new Message();
							m.what = StoreQRCScanByZLJY.SCANSUCCESS;
							hanlder.sendMessage(m);
						}
						else {
							Message m = new Message();
							m.what = StoreQRCScanByZLJY.SCANERROR;
							hanlder.sendMessage(m);
						}

					}


				}
			}.start();

		}
	}

	// 上传数据至服务器
	private boolean uploadInfo(List<Mothsked> li) {

		boolean bl = false;

		for (int i = 0; i < li.size(); i++) {
			Mothsked n = li.get(i);
			String jsonStr = mothsked.ConvertToJson(n);

			try {

				/****************** 调用webService ***********************/
				// 调用.net 的WebService.
				String nameSpace = "http://dyjapp.org/";
				String methodName = "UpdateMonthskedMstatus";


				SharedPreferences sPreferencces = getSharedPreferences(
						WEBSERVICE_CONFIG, 0);

				String url = "http://" + sPreferencces.getString("ip", "")
						+ ":" + sPreferencces.getString("Port", "")
						+ "/StoreService.asmx";// "http://192.168.1.101/webservice/default.asmx";
				// // 10.0.2.2
				// 为Android模拟器的本地(localhost)IP
				String soapAction = nameSpace + methodName;

				// 设置连接参数
				SoapObject request = new SoapObject(nameSpace, methodName);

				// 增加属性参数。 将相关的函数参数放入到过程中。
				request.addProperty("modelJson", jsonStr);


				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
						SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
				// V1.1）;

				// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
				// 不指定rpc方式则用true否则要用false
				envelope.dotNet = true;

				// envelope.setOutputSoapObject(request);//设置请求参数
				envelope.bodyOut = request; // enveloper.bodyOut=request 与
				// envelope.setOutputSoapObject(request)
				// 效果相同。
				// step4 创建HttpTransportSE对象
				HttpTransportSE ht = new HttpTransportSE(url);
				// step5 调用WebService
				ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
				if (envelope.getResponse() != null) {
					SoapPrimitive response = (SoapPrimitive) envelope
							.getResponse();
					if (!("0".equals(response.toString()))) {
						bl = true;
					}

				}
				/****************** 调用webService结束 ***********************/

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		return bl;
	}

}